package com.powerbank.admin.controller;

import com.powerbank.common.result.Result;
import com.powerbank.admin.dto.AdminLoginDTO;
import com.powerbank.admin.service.AdminAuthService;
import com.powerbank.admin.vo.AdminLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 管理员认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/auth")
public class AdminAuthController {

    @Autowired
    private AdminAuthService adminAuthService;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public Result<AdminLoginVO> login(@RequestBody @Valid AdminLoginDTO loginDTO) {
        try {
            AdminLoginVO result = adminAuthService.login(loginDTO);
            return Result.success("登录成功", result);
        } catch (Exception e) {
            log.error("管理员登录失败：{}", e.getMessage(), e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 管理员登出
     */
    @PostMapping("/logout")
    public Result<Void> logout(@RequestHeader("Authorization") String token) {
        try {
            boolean success = adminAuthService.logout(token);
            return success ? Result.<Void>success(null) : Result.<Void>error("登出失败");
        } catch (Exception e) {
            log.error("管理员登出失败：{}", e.getMessage(), e);
            return Result.<Void>error("登出失败：" + e.getMessage());
        }
    }

    /**
     * 刷新Token
     */
    @PostMapping("/refresh")
    public Result<AdminLoginVO> refreshToken(@RequestHeader("Authorization") String token) {
        try {
            AdminLoginVO result = adminAuthService.refreshToken(token);
            return Result.success("Token刷新成功", result);
        } catch (Exception e) {
            log.error("Token刷新失败：{}", e.getMessage(), e);
            return Result.<AdminLoginVO>error("Token刷新失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前登录管理员信息
     */
    @GetMapping("/info")
    public Result<AdminLoginVO> getCurrentAdminInfo(@RequestHeader("Authorization") String token) {
        try {
            AdminLoginVO result = adminAuthService.getCurrentAdminInfo(token);
            return Result.success("获取管理员信息成功", result);
        } catch (Exception e) {
            log.error("获取管理员信息失败：{}", e.getMessage(), e);
            return Result.<AdminLoginVO>error("获取管理员信息失败：" + e.getMessage());
        }
    }
}